from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.http import JsonResponse
from .models import User
from .forms import UserProfileForm, UserRegisterForm

# 新增视图函数
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from .forms import UserProfileForm
from .models import UserProfile

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            UserProfile.objects.create(user=user)
            login(request, user)
            messages.success(request, '注册成功！')
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'users/register.html', {'form': form})

@login_required
def profile(request):
    try:
        profile = request.user.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, '个人资料更新成功！')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=profile)

    return render(request, 'users/profile.html', {
        'form': form,
        'profile': profile
    })

@login_required
def change_password(request):
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        if not request.user.check_password(old_password):
            messages.error(request, '原密码不正确')
            return redirect('change_password')

        if new_password != confirm_password:
            messages.error(request, '两次输入的新密码不一致')
            return redirect('change_password')

        request.user.set_password(new_password)
        request.user.save()
        messages.success(request, '密码修改成功，请重新登录')
        return redirect('login')

    return render(request, 'users/change_password.html')

# 原有的视图函数
def home(request):
    """首页视图"""
    return render(request, 'index.html')

def register(request):
    """用户注册视图"""
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'账号 {username} 已成功创建！请登录。')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'register.html', {'form': form})

@login_required
def profile(request):
    """用户个人信息视图"""
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息更新成功！')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=request.user)

    # 获取最近5个订单
    recent_orders = request.user.order_set.all().order_by('-created_at')[:5]

    context = {
        'form': form,
        'recent_orders': recent_orders
    }
    return render(request, 'users/profile.html', context)

@login_required
def edit_profile(request):
    """编辑个人信息视图"""
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息更新成功！')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=request.user)
    return render(request, 'edit_profile.html', {'form': form})

@login_required
def change_password(request):
    """修改密码视图"""
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, '密码修改成功！')
            return redirect('profile')
        else:
            messages.error(request, '请更正下面的错误。')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {'form': form})

@login_required
def address_list(request):
    """收货地址列表视图"""
    addresses = request.user.address_set.all()
    return render(request, 'address_list.html', {'addresses': addresses})

@login_required
def add_address(request):
    """添加收货地址视图"""
    if request.method == 'POST':
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        is_default = request.POST.get('is_default', False)

        if is_default == 'true':
            # 将其他地址设置为非默认
            request.user.address_set.update(is_default=False)

        request.user.address_set.create(
            address=address,
            phone=phone,
            is_default=is_default
        )
        return JsonResponse({'status': 'success'})
    return render(request, 'add_address.html')
